<?php


namespace App\Models\Admin;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Support\Facades\Schema;
use Spatie\Permission\Models\Role as RoleModel;
use Spatie\Permission\Traits\HasRoles;

class Role extends RoleModel
{
    use HasRoles;

    protected $table = 'roles';
    protected $fillable = ["name", "guard_name", "site_id","is_system"];
    public $timestamps = true;    //自动管理时间戳
    protected $dateFormat = "U";  //时间样式


    protected $scopeLimit = true;//数据查询范围,设置为true时,数据查询将自动增加site_id条件
    protected $declares = [
        "name" => ["name", "like"]
    ];
    protected $casts = [
        'email_verified_at' => 'datetime',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
        'survival_time' => 'datetime:Y-m-d H:i:s'
    ];


    public function registerGlobalScopes($builder) {
        //自定义模型自动添加内置条件,可以通过 Model::withoutGlobalScope('site_id_scope')形式去除
        if ($this->scopeLimit && Schema::hasColumn($this->table, 'site_id')) {
            static::addGlobalScope('site_id_scope', function (Builder $builder) {
                $siteId = getCurrentSiteId();
                $builder->where('site_id', '=', $siteId);
            });
        }

        foreach ($this->getGlobalScopes() as $identifier => $scope) {
            $builder->withGlobalScope($identifier, $scope);
        }
        return $builder;
    }

    /**
     * 判断模型中是否存在某字段
     * @param string $column
     * @return bool
     */
    public function hasColumn($column) {
        return Schema::hasColumn($this->table, $column);
    }

    /**
     * 统一条件传入
     * @param array|null $condition
     * @return mixed
     */
    public function whereBuilder(array $condition = null) {
        $where = [];
        if ($condition) {
            foreach ($condition as $k => $v) {
                if (in_array($k, array_keys($this->declares))) {
                    $where[] = array_merge($this->declares[$k], [$v]);
                }
            }
        }
        return $this->where($where);
    }


    //获取全部
    public function getAll($where = [], $size = 12) {
        //平台
        if (getCurrentSiteId() == 0) {
            return self::whereBuilder($where)->withoutGlobalScope('site_id_scope')->with('site')->where("site_id", getCurrentSiteId())->orWhere("guard_name", "system")->paginate($size)->toArray();
        }
        //站点
        return self::whereBuilder($where)->withoutGlobalScope('site_id_scope')->with('site')->where("guard_name", "admin")->where(function ($query) {
            $query->where("site_id", getCurrentSiteId())->orWhere("site_id", 0);
        })->paginate($size)->toArray();

    }

    //覆盖父类创建
    public static function create(array $attributes = []) {
        // TODO: Change the autogenerated stub
        return static::query()->create($attributes);
    }

    //查找对应站点的角色
    public static function hasRole($name, $site_id) {
        return self::where("name", $name)->where("site_id", $site_id)->first();
    }

    //删除角色
    public function destoryOne($id) {
        return self::where("id", $id)->where("is_system", 0)->delete();
    }

    //获取单一角色
    public function getOne($id) {
        return self::withoutGlobalScope('site_id_scope')->find($id);
    }

    //修改角色
    public function change($params, $id) {
        return self::where('id', $id)->where("is_system", "!=", 1)->update($params);
    }

    //获取角色详情
    public function info(Role $role) {
        return self::with(['site', 'user'])->where("id", $role->id)->first()->toArray();
    }

    //获取角色对象
    public function role_obj($id) {
        return self::withoutGlobalScope('site_id_scope')->find($id);
    }

    //获取不分页的本站的所有角色
    public function get_roles() {
        //平台
        if (getCurrentSiteId() == 0) {
            return self::withoutGlobalScope('site_id_scope')->where("site_id", getCurrentSiteId())->orWhere("guard_name", "system")->get()->toArray();
        }
        //站点
        return self::withoutGlobalScope('site_id_scope')->where("guard_name", "admin")->where(function ($query) {
            $query->where("site_id", getCurrentSiteId())->orWhere("site_id", 0);
        })->get()->toArray();
    }

    //获取站点信息(多对一)
    public function site() {
        return $this->hasOne(Site::class, "id", "site_id");
    }

    //角色对用户（多对多）
    public function user() {
        return $this->belongsToMany("App\Models\Admin\AdminUser", "model_has_roles", "role_id", "model_id");
    }
}
